import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart' as PermissionHandler;
import 'package:permission_handler/permission_handler.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/plugins/xindong_to_native_plugin.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';
import 'package:xindong/widgets/dialog/xindong_base_alert.dart';

// ======== 应用权限
enum XinDongAppPermission {
  audio,
  camera,
  location,
  microphone,
  notification,
  photos,
  storage,
  videos,
}

class XinDongPermissionCtr extends GetxController {
  static XinDongPermissionCtr get to => Get.find();

  // 显示过开启定位提示，关闭后不显示
  bool showLocationReminder = true;

  // 是否允许通知
  bool enableNotification = false;

  // 是否允许定位
  bool enableLocationServices = true;

  // 是否开启位置服务
  bool enablePositioningSystem = true;

  void setup() async {
    enableNotification = await Permission.notification.isGranted;
    enableLocationServices = await Permission.location.isGranted;
    enablePositioningSystem = await XinDongToNativePlugin.instance.enablePositioningSystem();
    update();
  }

  // 打开应用设置页
  static openAppSettings() {
    PermissionHandler.openAppSettings();
  }

  static Future<bool> checkPermission(XinDongAppPermission type) async {
    //当前权限
    late Permission? permission;
    String name = '';
    String desc = '';
    switch (type) {
      case XinDongAppPermission.location:
        permission = Permission.locationWhenInUse;
        name = '位置';
        desc = '用于设置所在城市、匹配附近用户等场景';
        break;
      case XinDongAppPermission.camera:
        permission = Permission.camera;
        name = '相机';
        desc = '用于设置头像、发动态、聊天、上传相册等场景';
        break;
      case XinDongAppPermission.microphone:
        permission = Permission.microphone;
        name = '麦克风';
        desc = '用于录音，语言聊天等场景';
        break;
      case XinDongAppPermission.notification:
        if (Platform.isIOS) {
          permission = Permission.notification;
        } else {
          name = '推送通知';
          desc = '用于获取接收消息推送、平台资讯等场景';
          return openAppSettings();
        }
        break;
      case XinDongAppPermission.storage:
        if (Platform.isAndroid) {
          final androidInfo = await DeviceInfoPlugin().androidInfo;
          if (androidInfo.version.sdkInt <= 32) {
            permission = Permission.storage;
            name = '存储';
            desc = '用于获取相册图片视频，设置头像、发动态、聊天等场景';
          } else {
            return true;
            // permission = Permission.manageExternalStorage;
          }
        } else {
          return true;
        }
        break;
      case XinDongAppPermission.audio:
      case XinDongAppPermission.photos:
      case XinDongAppPermission.videos:
        {
          if (Platform.isAndroid) {
            final androidInfo = await DeviceInfoPlugin().androidInfo;
            if (androidInfo.version.sdkInt <= 32) {
              permission = Permission.storage;
              name = '存储';
              desc = '用于获取相册图片视频，设置头像、发动态、聊天等场景';
            } else if (type == XinDongAppPermission.audio) {
              permission = Permission.audio;
              name = '音频';
              desc = '用于聊天、通话等场景';
            } else if (type == XinDongAppPermission.videos) {
              permission = Permission.videos;
              name = '视频';
              desc = '用于获取相册视频，聊天等场景';
            } else if (type == XinDongAppPermission.photos) {
              permission = Permission.photos;
              name = '照片';
              desc = '用于获取相册图片，设置头像、发动态、聊天等场景';
            }
          } else {
            permission = Permission.photos;
          }
        }
        break;
    }

    if (permission == null) {
      return false;
    }

    //权限的状态
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      mDebugPrint('已经获得权限');
      return true;
    } else if (status.isDenied) {
      if (Platform.isAndroid) {
        BananaPermissionTipsDialog.show(name: name, desc: desc);
      }
      //发起权限申请
      PermissionStatus status = await permission.request();
      BananaPermissionTipsDialog.hide();
      if (status.isGranted) {
        return true;
      } else if (status.isPermanentlyDenied) {
        await XinDongAlertMessage.delayShow(
            title: "系统提醒",
            button: "确定",
            content: "您已经拒绝使用《$name》权限\n需要去手机系统设置开启",
            onTapButton: () {
              if (type == XinDongAppPermission.location) {
                // XinDongGaoDeMap.to.isBackstage = true;
              }
              XinDongPermissionCtr.openAppSettings();
            });
      } else {
        return false;
      }
    } else if (status.isPermanentlyDenied) {
      mDebugPrint('拒绝并不再提醒');
      await XinDongAlertMessage.delayShow(
          title: "系统提醒",
          button: "确定",
          content: "您已经拒绝使用《$name》权限\n需要去手机系统设置开启",
          onTapButton: () {
            XinDongPermissionCtr.openAppSettings();
          });
      return false;
    }
    return false;
  }
}

class BananaPermissionTipsDialog extends StatelessWidget {
  final String name;
  final String desc;

  const BananaPermissionTipsDialog({super.key, required this.name, required this.desc});

  static const String kTag = "PermissionTips";

  BananaPermissionTipsDialog.show({super.key, required this.name, required this.desc}) {
    showSmartAlert(alert: this, tag: kTag, useAnimation: false);
  }

  static hide() {
    SmartDialog.dismiss(tag: kTag);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.only(left: 20, right: 20, bottom: 46),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
        child: Text("$name权限使用说明：\n$desc", style: const TextStyle(height: 1.2)),
      ),
    );
  }
}
